<?php
/**
 * 程序启动命令
 *
 *
 */
class BootInit{
    private $_controller = NULL;
    private $_action = NULL;
    private $_params = array();
    private $default = array();
    private static $_instance = null;
    private $_errorLog = 'error.log';

    /*
     * 错误日志记录
     *
     * @return void
     */
    private function _setError()
    {
        error_reporting(E_ALL);
        ini_set('log_errors', 'On');
        defined('DEBUG') && ini_set('display_errors', intval(DEBUG));

        if (!empty($this->default['errorLog']) && file_exists($this->default['errorLog'])) {
            $errorLog = $this->default['errorLog'];
        } else {
            $errorLog = ROOT_PATH . '/logs/'. $this->_errorLog; 
        }
        ini_set('error_log', $errorLog);

    }

    /**
     * 启动初始化
     * 加载配置文件
     *
     * @return void
     */    
    private function __construct(){

        $this->default = LibsCommon::getConfig(); //加载配置文件
        define('DEBUG', $this->default['debug']);

        $this->_setError();
        
        date_default_timezone_set($this->default['timezone']);
    
        if(empty($this->default['defaultController'])){
            //系统默认的值
            $this->_controller = 'test';
        }else{
            //您配置的默认值
            $this->_controller = $this->default['defaultController'];
        }
        
        $this->_routeUrl();
    }
    
    /*
     * 从url提取controller，action，params
     *
     * @return boolean
     */
    private function _routeUrl(){

        $routeArr = explode('/', $_SERVER['PHP_SELF']);
        $indexKey = array_search('index.php', $routeArr);
        //采用默认crontroller action
        if ($indexKey === false) {
            return false;
        }

        //命令行运行
        if (php_sapi_name() == 'cli') {
            isset($_SERVER['argv'][1]) && ($this->_controller = $_SERVER['argv'][1]);
            isset($_SERVER['argv'][2]) && ($this->_action = $_SERVER['argv'][2]);
            isset($_SERVER['argv'][3]) && ($this->_params = array_slice($_SERVER['argv'], 3));
        } else {
            isset($routeArr[$indexKey+1]) && ($this->_controller = $routeArr[$indexKey+1]);
            isset($routeArr[$indexKey+2]) && ($this->_action = $routeArr[$indexKey+2]);
            isset($routeArr[$indexKey+3]) && ($this->_params = array_slice($routeArr, $indexKey+3));
        }

        //转换index.php/admin-login/index  
        //index.php/adminLogin/index 
        //index.php/admin_login/index
        $this->_controller = preg_replace_callback(
            '#[\-\_]([a-z])#', 
            create_function('$match', 'return strtoupper($match[1]);'),
            $this->_controller
        );

        return true;
    }
    
    /*
     * 启动程序，查找相应的文件controller，action
     *
     * @return boolean
     */
    public function start(){
        //$this->controller 为 test ，而对应的类名为ControllerTest
        $className = "Controllers".ucfirst($this->_controller);
        if(!class_exists($className)) {
            throw new Exception("controller:{$this->_controller} 不存在！");
            return false;
        }

        $action = $this->_action;
        if(!empty($action) && !method_exists($className, $action)){
            throw new Exception("controller:{$this->_controller} 不存在action:{$this->_action}方法！");
            return false;
        }

        $ctrl = new $className();
        $action = empty($action)?$ctrl->defaultAction:$action;

        //命令行运行
        if (php_sapi_name() == 'cli') {
            call_user_func_array(array($ctrl, $action), $this->_params);
            return true;
        }
        call_user_func_array(array($ctrl, 'output'), array($action, $this->_params));
        return true;
    }

    /**
     * 实例化
     *
     */
    public static function getInstance() {
        if (empty(self::$_instance)) {
            $className = __CLASS__;
            self::$_instance = new $className();
        }        
        return self::$_instance;
    }
}
